package cn.gyn.gynrpc.core.registry.gyn;

import cn.gyn.gynrpc.core.consumer.HttpInvoker;
import cn.gyn.gynrpc.core.meta.InstanceMeta;
import cn.gyn.gynrpc.core.registry.Events;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * check health for registry center
 * 多线程相关的代码
 */
@Slf4j
public class GynHealthChecker {

    //该定时任务调度给consumer用的,在start里实例化，在stop里停下来
    ScheduledExecutorService consumerExecutor = null;
    //该定时任务调度给provider用的
    ScheduledExecutorService providerExecutor = null;

    public void start() {
        log.info("===========>>>> [gynregistry] : start with health checker.");
        //定时任务实例化
        consumerExecutor = Executors.newScheduledThreadPool(1);
        providerExecutor = Executors.newScheduledThreadPool(1);
    }

    public void stop() {
        log.info(" =====> [gynregistry] : stop with health checker.");

        //region 优雅停机：常规线程启停写法：先shutdown，1秒后判断如果没有停下来，就shutdownNow强制停(注意：1个gracefulShutdown等1s，2个等2秒，以此类推)
        gracefulShutdown(consumerExecutor);
        gracefulShutdown(providerExecutor);
    }

    public void consumerCheck(Callback callback) {
        consumerExecutor.scheduleAtFixedRate(() -> {
            try{
                callback.call();
            } catch (Exception e) {
                log.error("===========>>>> [gynregistry] : consumer check failed", e);
            }
        }, 1, 5, TimeUnit.SECONDS);
    }

    public void providerCheck(Callback callback) {
        //provider 每5s调用renew探活
        providerExecutor.scheduleAtFixedRate(() -> {
            try{
                callback.call();
            } catch (Exception e) {
                log.error("===========>>>> [gynregistry] : provider check failed", e);
            }
        }, 5, 5, TimeUnit.SECONDS);
    }

    private static void gracefulShutdown(ScheduledExecutorService executor) {
        executor.shutdown();
        try {
            //先shutdown，1秒后判断如果没有停下来，就shutdownNow强制停
            executor.awaitTermination(1000, TimeUnit.MILLISECONDS);
            //isTerminated比isShutdown 精确一些
            if (!executor.isTerminated()) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // ignore
        }
    }

    /**
     * 将一段执行器里要用到的方法，封装一个lambda表达式：一个lambda表达式可以用只有一个方法的接口来表示
     */
    public interface Callback {
        void call() throws Exception;
    }

}
